package com.ykdl.member.kid.chat;

import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ykdl.member.constant.KidAction;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.adapters.MessageChatAdapter;
import com.ykdl.member.kid.beans.Actor_conversationBean;
import com.ykdl.member.kid.beans.ArticleBean;
import com.ykdl.member.kid.beans.ChatBean;
import com.ykdl.member.kid.beans.ChatBeanList;
import com.ykdl.member.kid.beans.ChatUpload;
import com.ykdl.member.kid.beans.FileBean;
import com.ykdl.member.kid.beans.JsonChatBean;
import com.ykdl.member.kid.beans.ResetPasswordBean;
import com.ykdl.member.kid.gears.BaseScreen;
import com.ykdl.member.kid.prefs.MyPrefs;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.IsConnent;
import com.ykdl.member.kid.xlist.XListView;
import com.ykdl.member.kid.xlist.XListView.IXListViewListener;
import com.ykdl.member.views.EmoticonsEditText;
import com.ykdl.member.views.dialog.DialogTips;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

public class ChatActivity extends BaseScreen implements OnClickListener,IXListViewListener{
	

	private Button btn_chat_emo, btn_chat_send, btn_chat_add,btn_chat_keyboard, btn_speak;

	private XListView mListView;

	private EmoticonsEditText edit_user_comment;
	
	private LinearLayout layout_more, layout_emo, layout_add;

	private ViewPager pager_emo;

	private TextView tv_picture, tv_camera, tv_location;
	
	private MessageChatAdapter mAdapter;
	private SocketIO socket;
	private Actor_conversationBean conversationBean;
	private static AccessTokenKeeper mTokenKeeper;
	private SendChatCallback callback= new SendChatCallback();
	private String cooperative_corp_id ;
	private String title_name ;
	private int cursor = 0;
	private int count = 20;
	String url="";
	private ArrayList<ChatBean> list =new ArrayList<ChatBean>();
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setTopTitle("", 0, R.drawable.back_bg, new OnClickListener() {
			@Override
			public void onClick(View v) {
				markReadMessage();
//					finish();
				
			}
		}, 0, 0, null, R.drawable.title_bg, false);
		cooperative_corp_id= this.getIntent().getStringExtra(KidAction.COOPERATIVE_CORP_ID);
		title_name = this.getIntent().getStringExtra(KidAction.SEVRVER_NAME);
		setContent(R.layout.activity_chat);
		initView();
		}
	private void initView() {
		mListView = (XListView) findViewById(R.id.mListView);
		setTopNav("与" +title_name+ "对话");
		initBottomView();
		initXListView();
		inintSocketIO();
	}
	public void inintSocketIO() {
		mTokenKeeper = new AccessTokenKeeper(this);
		if (!MyPrefs.getweb_socket(this).equals("")) {
			 url=MyPrefs.getweb_socket(this)+"?access_token="+mTokenKeeper.getmAccessToken()+"&app_key=hsh";
			try {
				socket = new SocketIO(url);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			socket.connect(callback);
//			socket.connect(callback) {
//
//
//
//				@Override
//				public void onDisconnect() {
//					// TODO Auto-generated method stub
//					
//				}
//
//				@Override
//				public void onError(SocketIOException arg0) {
//					// TODO Auto-generated method stub
//					Log.e("Alan", "--connect--onError");
//				}
//
//				@Override
//				public void onMessage(String arg0, IOAcknowledge arg1) {
//					// TODO Auto-generated method stub
//					Log.e("Alan", "--connect--onMessage-String");
//				}
//
//				@Override
//				public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
//					// TODO Auto-generated method stub
//					Log.e("Alan", "--connect--onMessage-JSONObject:"+arg0.toString());
////					Gson   gson = null;
////					if(null != arg0){
////						GsonBuilder b = new GsonBuilder();
////						gson  = b.create();
////					}
////					ChatBean bean =gson.fromJson(arg0.toString(), ChatBean.class);
////					refreshMessage(bean);
////					finishProgress();
////					initMsgData();
////					Log.e("Alan", "--connect--onMessage-ChatBean:"+bean.getContent());
//				}
//				
//			});
		}
		
	}
	private void initBottomView() {
		// 最左边
		btn_chat_add = (Button) findViewById(R.id.btn_chat_add);
		btn_chat_emo = (Button) findViewById(R.id.btn_chat_emo);
		btn_chat_add.setOnClickListener(this);
		btn_chat_emo.setOnClickListener(this);
		// 最右边
		btn_chat_keyboard = (Button) findViewById(R.id.btn_chat_keyboard);
		btn_chat_keyboard.setOnClickListener(this);
		btn_chat_send = (Button) findViewById(R.id.btn_chat_send);
		btn_chat_send.setOnClickListener(this);
		// 最下面
		layout_more = (LinearLayout) findViewById(R.id.layout_more);
		layout_emo = (LinearLayout) findViewById(R.id.layout_emo);
		layout_add = (LinearLayout) findViewById(R.id.layout_add);
		initAddView();
//		initEmoView();

		// 最中间
		// 语音框
		btn_speak = (Button) findViewById(R.id.btn_speak);
		// 输入框
		edit_user_comment = (EmoticonsEditText) findViewById(R.id.edit_user_comment);
		edit_user_comment.setOnClickListener(this);
		btn_chat_keyboard.setVisibility(View.GONE);
//		edit_user_comment.addTextChangedListener(new TextWatcher() {
//
//			@Override
//			public void onTextChanged(CharSequence s, int start, int before,
//					int count) {
//				// TODO Auto-generated method stub
//				if (!TextUtils.isEmpty(s)) {
//					btn_chat_send.setVisibility(View.VISIBLE);
//					btn_chat_keyboard.setVisibility(View.GONE);
//					btn_chat_voice.setVisibility(View.GONE);
//				} else {
//					if (btn_chat_voice.getVisibility() != View.VISIBLE) {
//						btn_chat_voice.setVisibility(View.VISIBLE);
//						btn_chat_send.setVisibility(View.GONE);
//						btn_chat_keyboard.setVisibility(View.GONE);
//					}
//				}
//			}
//
//			@Override
//			public void beforeTextChanged(CharSequence s, int start, int count,
//					int after) {
//				// TODO Auto-generated method stub
//
//			}
//
//			@Override
//			public void afterTextChanged(Editable s) {
//				// TODO Auto-generated method stub
//			}
//		});

	}
	private void initAddView() {
		tv_picture = (TextView) findViewById(R.id.tv_picture);
		tv_camera = (TextView) findViewById(R.id.tv_camera);
		tv_location = (TextView) findViewById(R.id.tv_location);
		tv_picture.setOnClickListener(this);
		tv_location.setOnClickListener(this);
		tv_camera.setOnClickListener(this);
	}
	
	private void initXListView() {
		// 首先不允许加载更多
		mListView.setPullLoadEnable(false);
		// 允许下拉
		mListView.setPullRefreshEnable(true);
		// 设置监听器
		mListView.setXListViewListener(this);
		mListView.pullRefreshing();
		mListView.setDividerHeight(0);
		// 加载数据
		initOrRefresh();
		mAdapter= new MessageChatAdapter(this, new ArrayList<ChatBean>());
		mListView.setAdapter(mAdapter);
		mListView.setSelection(mAdapter.getCount() - 1);
		mListView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
//				hideSoftInputView();
				layout_more.setVisibility(View.GONE);
				layout_add.setVisibility(View.GONE);
				btn_chat_keyboard.setVisibility(View.GONE);
				return false;
			}
		});

		// 重发按钮的点击事件
		mAdapter.setOnInViewClickListener(R.id.iv_fail_resend,
				new MessageChatAdapter.onInternalClickListener() {

					@Override
					public void OnClickListener(View parentV, View v,
							Integer position, Object values) {
						// 重发消息
						showResendDialog(parentV, v, values);
					}
				});
	}
	/**
	 * 显示重发按钮 showResendDialog
	 * @Title: showResendDialog
	 * @Description: TODO
	 * @param @param recent
	 * @return void
	 * @throws
	 */
	public void showResendDialog(final View parentV, View v, final Object values) {
		DialogTips dialog = new DialogTips(this, "确定重发该消息", "确定", "取消", "提示",
				true);
		// 设置成功事件
		dialog.SetOnSuccessListener(new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialogInterface, int userId) {
				if (((ChatBean) values).getAttachment_type() == ChatConfig.TYPE_IMAGE
						) {// 图片类型的采用
					resendFileMsg(parentV, values);
				} else {
					resendTextMsg(parentV, values);
				}
				dialogInterface.dismiss();
			}
		});
		// 显示确认对话框
		dialog.show();
		dialog = null;
	}
	/**
	 * 重发图片消息
	 * @Title: resendImageMsg
	 * @Description: TODO
	 * @param @param parentV
	 * @param @param values
	 * @return void
	 * @throws
	 */
	private void resendFileMsg(final View parentV, final Object values) {
		/*BmobChatManager.getInstance(ChatActivity.this).resendFileMessage(
				targetUser, (BmobMsg) values, new UploadListener() {

					@Override
					public void onStart(BmobMsg msg) {
						// TODO Auto-generated method stub
					}

					@Override
					public void onSuccess() {
						// TODO Auto-generated method stub
						((BmobMsg) values)
								.setStatus(BmobConfig.STATUS_SEND_SUCCESS);
						parentV.findViewById(R.id.progress_load).setVisibility(
								View.INVISIBLE);
						parentV.findViewById(R.id.iv_fail_resend)
								.setVisibility(View.INVISIBLE);
						if (((BmobMsg) values).getMsgType() == BmobConfig.TYPE_VOICE) {
							parentV.findViewById(R.id.tv_send_status)
									.setVisibility(View.GONE);
							parentV.findViewById(R.id.tv_voice_length)
									.setVisibility(View.VISIBLE);
						} else {
							parentV.findViewById(R.id.tv_send_status)
									.setVisibility(View.VISIBLE);
							((TextView) parentV
									.findViewById(R.id.tv_send_status))
									.setText("已发送");
						}
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						// TODO Auto-generated method stub
						((BmobMsg) values)
								.setStatus(BmobConfig.STATUS_SEND_FAIL);
						parentV.findViewById(R.id.progress_load).setVisibility(
								View.INVISIBLE);
						parentV.findViewById(R.id.iv_fail_resend)
								.setVisibility(View.VISIBLE);
						parentV.findViewById(R.id.tv_send_status)
								.setVisibility(View.INVISIBLE);
					}
				});*/
		mAdapter.notifyDataSetChanged();
	}
	/**
	 * 重发文本消息
	 */
	private void resendTextMsg(final View parentV, final Object values) {
		/*BmobChatManager.getInstance(ChatActivity.this).resendTextMessage(
				targetUser, (BmobMsg) values, new PushListener() {

					@Override
					public void onSuccess() {
						// TODO Auto-generated method stub
						ShowLog("发送成功");
						((BmobMsg) values)
								.setStatus(BmobConfig.STATUS_SEND_SUCCESS);
						parentV.findViewById(R.id.progress_load).setVisibility(
								View.INVISIBLE);
						parentV.findViewById(R.id.iv_fail_resend)
								.setVisibility(View.INVISIBLE);
						parentV.findViewById(R.id.tv_send_status)
								.setVisibility(View.VISIBLE);
						((TextView) parentV.findViewById(R.id.tv_send_status))
								.setText("已发送");
					}

					@Override
					public void onFailure(int arg0, String arg1) {
						// TODO Auto-generated method stub
						ShowLog("发送失败:" + arg1);
						((BmobMsg) values)
								.setStatus(BmobConfig.STATUS_SEND_FAIL);
						parentV.findViewById(R.id.progress_load).setVisibility(
								View.INVISIBLE);
						parentV.findViewById(R.id.iv_fail_resend)
								.setVisibility(View.VISIBLE);
						parentV.findViewById(R.id.tv_send_status)
								.setVisibility(View.INVISIBLE);
					}
				});*/
		mAdapter.notifyDataSetChanged();
	}
	
	public static final int NEW_MESSAGE = 0x001;// 收到消息
	public static final int MESSAG_SEND_FAIL = 0x002;// 收到消息
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == NEW_MESSAGE) {
				finishProgress();
				ChatBean message = (ChatBean) msg.obj;
				refreshMessage(message);
				// 定位
				
			}else if(msg.what == MESSAG_SEND_FAIL){
				finishProgress();
			}
		}
	};
	/**
	 * 界面刷新
	 * @Title: initOrRefresh
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 */
	private void initOrRefresh() {

//		mAdapter = new MessageChatAdapter(this, initMsgData());
//		mListView.setAdapter(mAdapter);
		initMsgData(false) ;

	}
//	/**
//	 * 加载消息
//	 */
//	private ArrayList<ChatBean> initMsgData() {
//		ArrayList<ChatBean> list = new  ArrayList<ChatBean>();
//		return list;
//	}
	/**
	 * 根据是否点击笑脸来显示文本输入框的状态
	 * @Title: showEditState
	 * @Description: TODO
	 * @param @param isEmo: 用于区分文字和表情
	 * @return void
	 * @throws
	 */
	private void showEditState(boolean isEmo) {
		edit_user_comment.setVisibility(View.VISIBLE);
		btn_chat_keyboard.setVisibility(View.GONE);
		btn_speak.setVisibility(View.GONE);
		edit_user_comment.requestFocus();
		if (isEmo) {
			layout_more.setVisibility(View.VISIBLE);
			layout_more.setVisibility(View.VISIBLE);
			layout_emo.setVisibility(View.VISIBLE);
			layout_add.setVisibility(View.GONE);
			hideSoftInputView();
		} else {
			layout_more.setVisibility(View.GONE);
			showSoftInputView();
		}
	}

	// 显示软键盘
	public void showSoftInputView() {
		if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getCurrentFocus() != null)
				((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
						.showSoftInput(edit_user_comment, 0);
		}
	}
	private String localCameraPath = "";// 拍照后得到的图片地址

	/**
	 * 启动相机拍照 startCamera
	 * 
	 * @Title: startCamera
	 * @throws
	 */
	public void selectImageFromCamera() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		File dir = new File(ChatConfig.BMOB_PICTURE_PATH);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir, String.valueOf(System.currentTimeMillis())
				+ ".jpg");
		localCameraPath = file.getPath();
		Uri imageUri = Uri.fromFile(file);
		openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(openCameraIntent,
				ChatConfig.REQUESTCODE_TAKE_CAMERA);
	}

	/**
	 * 选择图片
	 * @Title: selectImage
	 * @Description: TODO
	 * @param
	 * @return void
	 * @throws
	 */
	public void selectImageFromLocal() {
		 Intent intent = new Intent(Intent.ACTION_PICK, null);
         intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
        		 "image/*");
		startActivityForResult(intent, ChatConfig.REQUESTCODE_TAKE_LOCAL);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case ChatConfig.REQUESTCODE_TAKE_CAMERA:// 当取到值的时候才上传path路径下的图片到服务器
//				ShowLog("本地图片的地址：" + localCameraPath);
				sendImageMessage(localCameraPath);
				break;
			case ChatConfig.REQUESTCODE_TAKE_LOCAL:
				if (data != null) {
					Uri selectedImage = data.getData();
					String localSelectPath="";
					if (selectedImage != null) {
						Cursor cursor = getContentResolver().query(
								selectedImage, null, null, null, null);
						if (null!=cursor) {
							cursor.moveToFirst();
							int columnIndex = cursor.getColumnIndex("_data");
							 localSelectPath = cursor.getString(columnIndex);
							cursor.close();
						}else {
							localSelectPath=selectedImage.toString().substring("file://".length());
						}
						
						if (localSelectPath == null
								|| localSelectPath.equals("null")) {
							ShowToast("找不到您想要的图片");
							return;
						}
						sendImageMessage(localSelectPath);
					}
				}
				break;
			}
		}
	}
	
	/**
	 * 刷新界面
	 * @Title: refreshMessage
	 * @Description: TODO
	 * @param @param message
	 * @return void
	 * @throws
	 */
	private void refreshMessage(ChatBean msg) {
		// 更新界面
		mAdapter.add(msg);
		mListView.setSelection(mAdapter.getCount() - 1);
		edit_user_comment.setText("");
	}
	//接受到消息后
	public void onReMessage(ChatBean msg) {
		// TODO Auto-generated method stub
		Message handlerMsg = handler.obtainMessage(NEW_MESSAGE);
		handlerMsg.obj = msg;
		handler.sendMessage(handlerMsg);
	}
	public void onReError() {
		// TODO Auto-generated method stub
		Message handlerMsg = handler.obtainMessage(MESSAG_SEND_FAIL);
		handler.sendMessage(handlerMsg);
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.edit_user_comment:// 点击文本输入框
			mListView.setSelection(mListView.getCount() - 1);
			if (layout_more.getVisibility() == View.VISIBLE) {
				layout_add.setVisibility(View.GONE);
				layout_emo.setVisibility(View.GONE);
				layout_more.setVisibility(View.GONE);
			}
			break;
		case R.id.btn_chat_add:// 添加按钮-显示图片、拍照、位置
			if (layout_more.getVisibility() == View.GONE) {
				layout_more.setVisibility(View.VISIBLE);
				layout_add.setVisibility(View.VISIBLE);
				layout_emo.setVisibility(View.GONE);
				hideSoftInputView();
			} else {
				if (layout_emo.getVisibility() == View.VISIBLE) {
					layout_emo.setVisibility(View.GONE);
					layout_add.setVisibility(View.VISIBLE);
				} else {
					layout_more.setVisibility(View.GONE);
				}
			}

			break;
		case R.id.btn_chat_keyboard:// 键盘按钮，点击就弹出键盘并隐藏掉声音按钮
			showEditState(false);
			break;
		case R.id.btn_chat_send:// 发送文本
			final String msg = edit_user_comment.getText().toString();
			if (msg.equals("")) {
				ShowToast("发送内容不能为空，请重新输入!");
				return;
			}
			if (!isConnect(this)) {
				ShowToast(R.string.network_tips);
				 return;
			}
			// 组装BmobMessage对象
//			BmobMsg message = BmobMsg.createTextSendMsg(this, targetId, msg);
			// 默认发送完成，将数据保存到本地消息表和最近会话表中
//			manager.sendTextMessage(targetUser, message);
			// 刷新界面
			sedMessage(msg);
//			refreshMessage(makeMsg(msg,false));

			break;
		case R.id.tv_camera:// 拍照
			selectImageFromCamera();
			break;
		case R.id.tv_picture:// 图片
			selectImageFromLocal();
			break;
		default:
			break;
		}
	}

	public void sedMessage(String message) {
		showProgress("发送中,请稍等...");
		if (!isConnect(this)) {
			Toast.makeText(mContext, "没有网络", 1).show();
			return;
		}else {
			if (!socket.isConnected()) {
					socket.reconnect();
			}
		}
		Log.e("Alan", "---------socket-isConnected:" + socket.isConnected());
		JSONObject json = new JSONObject();
		JSONArray jarry = new JSONArray();
		SendChatCallback callback = new SendChatCallback();
		try {
			json.putOpt("conversation_id",
					conversationBean.getConversation_id());
			json.putOpt("actor_conversation_id",
					conversationBean.getActor_conversation_id());

			json.putOpt("attachment_type", 0);
			json.putOpt("content", message);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		socket.send(json.toString());
	}

	public void sedMessage(FileBean message) {
		showProgress("发送中,请稍等...");
		if (!socket.isConnected()) {
			Toast.makeText(mContext, "socket连接失败", 1).show();
			return;
		}
		Log.e("Alan", "---------socket-isConnected:" + socket.isConnected());
		JSONObject json = new JSONObject();
		JSONObject file = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		SendChatCallback callback = new SendChatCallback();
		try {
			json.putOpt("conversation_id",
					conversationBean.getConversation_id());
			json.putOpt("actor_conversation_id",
					conversationBean.getActor_conversation_id());
			json.putOpt("attachment_type", 1);
			json.putOpt("content", "");
			file.putOpt("file_id", message.getFile_id());
			file.putOpt("file_path", message.getFile_path());
			file.putOpt("url", message.getFile_url());
			jsonArray.put(file);
			json.putOpt("attachments", jsonArray);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		socket.send(json.toString());
	}
	
	class SendChatCallback implements IOCallback, IOAcknowledge {

		@Override
		public void ack(Object... arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void on(String arg0, IOAcknowledge arg1, Object... arg2) {
			// TODO Auto-generated method stub
			Log.e("Alan", "----------on---String:"+arg0.toString());
		}

		@Override
		public void onConnect() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onDisconnect() {
			// TODO Auto-generated method stub
			finishProgress();
		}

		@Override
		public void onError(SocketIOException arg0) {
			// TODO Auto-generated method stub
			finishProgress();
			Log.e("Alan", "----------onError---:"+arg0.toString());
			onReError();
		}

		@Override
		public void onMessage(String arg0, IOAcknowledge arg1) {
			// TODO Auto-generated method stub
			
			Log.e("Alan", "----------onMessage---String:"+arg0.toString());
		}

		@Override
		public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
			// TODO Auto-generated method stub
			Log.e("Alan", "----------finish---");
//			finishProgress();
			Gson   gson = null;
		if(null != arg0){
			GsonBuilder b = new GsonBuilder();
			gson  = b.create();
		}
		JsonChatBean bean =gson.fromJson(arg0.toString(), JsonChatBean.class);
		if (bean.getStatus()==0) {
			onReMessage(bean.getData());
			count++;
		}
			
//			initMsgData();
			Log.e("Alan", "----------onMessage---JSONObject:"+arg0.toString());
			
		}
		
	}
	
	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		initMsgData(true);
	}
	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		
	}
	/**
	 * 默认先上传本地图片，之后才显示出来 sendImageMessage
	 * @Title: sendImageMessage
	 * @Description: TODO
	 * @param @param localPath
	 * @return void
	 * @throws
	 */
	private void sendImageMessage(String local) {
		showProgress("发送中,请稍等...");
		if (layout_more.getVisibility() == View.VISIBLE) {
			layout_more.setVisibility(View.GONE);
			layout_add.setVisibility(View.GONE);
			layout_emo.setVisibility(View.GONE);
		}
		File file = new File(local);
		String  pageurl = KidConfig.UPLOAD_IMAGE;
		HttpBaseRequest request  =  Wxxr.getInstance().uploadAvatar(pageurl,file);
		 TaskManager.startHttpRequest(request, new putphotoTag(),  ChatUpload.class);
	}
//	public String mkString(FileBean file) {
//		String msg="";
//		return msg;
//	}
	
	class putphotoTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof ChatUpload) {
				ChatUpload bean = (ChatUpload)t;
				if (bean.getError()==null) {
					if (bean.getStatus()==0) {
						sedMessage(bean.getFile());
					}
					
				}
				
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			Toast.makeText(mContext, "图片上传失败", 1).show();
			mAdapter.notifyDataSetChanged();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	public void initMsgData(boolean isRefresh) {
		if (!isConnect(this)) {
			Toast.makeText(mContext, "没有网络", 1).show();
			return;
		}
		if (!isRefresh) {
			showProgress("正在加载中,请稍等...");
		}
		String  pageurl = KidConfig.GET_CONVERSATION;
		Map<String, String> map = new HashMap<String, String>();
		map.put("cursor", String.valueOf(cursor));
		map.put("count", String.valueOf(count));
		map.put("sig", "bigger_than_bigger");
		map.put("target_actor_id", cooperative_corp_id);
		HttpBaseRequest request  =  Wxxr.getInstance().getRequest(pageurl, map,null);
		 TaskManager.startHttpRequest(request, new getMsgDataTag(isRefresh),  ChatBeanList.class);
	}
	class getMsgDataTag implements ITag {
		private boolean isRefresh;
		public getMsgDataTag(boolean isRefresh) {
			this.isRefresh=isRefresh;
		}
		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			finishProgress();
			if (t instanceof ChatBeanList) {
				ChatBeanList bean = (ChatBeanList)t;
				if (bean.getError()==null) {
					conversationBean=bean.getActor_conversation();
					for (ChatBean obj : bean.getMessages()) {
						list.add(obj);
					}
					Collections.reverse(list);
					mAdapter.setList(list);
					count=list.size();
					mAdapter.notifyDataSetChanged();
					if (bean.getNext_cursor() == bean.getTotal_number()) {
					} else {
						cursor = bean.getNext_cursor();
					}
					if (!isRefresh) {
						mListView.setSelection(mAdapter.getCount() - 1);
					}
				}
				mListView.stopRefresh();
			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			finishProgress();
			mListView.stopRefresh();
			Toast.makeText(mContext, "加载失败", 1).show();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			
		}
		
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	public void markReadMessage() {
		if (null==conversationBean) {
			socket.disconnect();
			ChatActivity.this.finish();
			return;
		}
		showProgress("请稍等...");
		String pageurl = KidConfig.GET_CONVERSATION+"/"+conversationBean.getActor_conversation_id()+"/read";
		HttpBaseRequest request  =  Wxxr.getInstance().getRequest(pageurl, null);
		TaskManager.startHttpRequest(request, new markReadMessageTag(),  ResetPasswordBean.class);
	}
	class markReadMessageTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			ResetPasswordBean bean = (ResetPasswordBean)t;
			socket.disconnect();
			ChatActivity.this.finish();
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			// TODO Auto-generated method stub
			socket.disconnect();
			ChatActivity.this.finish();
			return false;
		}

		@Override
		public void refreshCancel() {
			// TODO Auto-generated method stub
			socket.disconnect();
			ChatActivity.this.finish();
		}
		
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		markReadMessage();
//		super.onBackPressed();
	}
}
